package com.zh.mediaservice.ws;

//import com.zh.mediaservice.config.HttpSessionConfig;
import com.alibaba.fastjson.JSON;
import com.zh.mediacommon.constant.MessageConstant;
import com.zh.mediacommon.constant.ReserveConstant;
import com.zh.mediacommon.util.MessageHandleUtil;
import com.zh.mediapojo.entity.Message;
import com.zh.mediaservice.config.HttpSessionConfig;
import com.zh.mediaservice.mapper.UserChatDoctorMapper;
import com.zh.mediaservice.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;

import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/consultation/{isUser}/{userId}", configurator = HttpSessionConfig.class)
@Slf4j
@Component
public class ConsultationSocket {

    private final static Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    private Long userId;
//    private boolean isUser;
    @Autowired
    MessageService messageService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserChatDoctorMapper userChatDoctorMapper;
    @OnOpen
    public void onOpen(@PathParam("userId") Long userId,@PathParam("isUser") boolean isUser, Session session, EndpointConfig config) throws InterruptedException {
       log.info("用户开始连接");
        try{
            log.info("用户{}开始连接",userId);
            this.userId = userId;
//            this.isUser = isUser;
            if (isUser)
                sessionMap.put("0"+userId, session);
            else {
                sessionMap.put("1" + userId, session);
                log.info("医生{}上线",userId);
                redisTemplate.opsForHash().put(ReserveConstant.DOCTOR_ONLINE, userId, LocalDateTime.now());
            }
            String key="";
            if(isUser)
                key="用户"+userId;
            else
                key="医生"+userId;
            boolean b = messageService.sendToUnreadMessages(key, session);
            if(isUser && !b)
                session.getBasicRemote().sendText(MessageConstant.DEFAULT_MESSAGE);
            log.info("用户{}连接成功",userId);
        }catch (Exception e){
                log.info("用户连接失败 原因{}", e.getMessage());
        }
    }
    @OnMessage
    public void onMessage(@PathParam("userId") Long userId ,@PathParam("isUser") boolean isUser, String message,Session session2) {
   try {
       log.info(message);
       sendMessage(message,session2);
       log.info("用户{}收到消息{}",isUser,message);
       //测试链接使用
//       Session session1;
//       Message message1 = JSON.parseObject(message, Message.class);
//       String message2 = MessageHandleUtil.getMessage(message1);
//       if(isUser)
//           session1= sessionMap.get("0"+userId);
//       else
//           session1= sessionMap.get("1"+userId);
//       if(session1 != null)
//           session1.getAsyncRemote().sendText(message2);
//       session2.getAsyncRemote().sendText(message2);
   }catch (Exception e){
       log.info("用户{}发送消息失败 原因{}",userId,e.getMessage());
   }
    }

    @OnClose
    public void onClose(@PathParam("userId") Long userId,@PathParam("isUser") boolean isUser) {
       log.info("用户{}断开连接",isUser);
        if(isUser)
            sessionMap.remove("0"+userId);
        else {
            sessionMap.remove("1" + userId);
            log.info("医生{}下线",userId);
            redisTemplate.opsForHash().delete(ReserveConstant.DOCTOR_ONLINE, userId);
        }
            log.info("连接关闭");
    }
    private void sendMessage(String message,Session session2) throws Exception{
            Message message1 = JSON.parseObject(message, Message.class);
//            message1.setSender(userId);
            Long userId = message1.getSender();
            log.info("sender{}{}", userId,message1.getUser());
            message1.setDate(LocalDateTime.now());
            Long did=message1.getReceiver();
            if(redisTemplate.opsForHash().get("chat"+userId,did)==null){
                userChatDoctorMapper.insert(userId,did,true);
                userChatDoctorMapper.insert(did,userId,false);
                redisTemplate.opsForHash().put("chat"+userId,did,1);
            }
            log.info("用户{}发送消息{}",message1.getSender(),message1);
            Session session;
            log.info("接收者{}",message1.getReceiver());
            if(message1.getUser())
                session = sessionMap.get("1"+message1.getReceiver());
            else
                session = sessionMap.get("0"+message1.getReceiver());
            String message2 = MessageHandleUtil.getMessage(message1);
            if(session != null) {
                session.getAsyncRemote().sendText(message2);
                //TODO 保存到数据库
                messageService.save(message1, message1.getUser());
            }else{
                //TODO 保存到redis数据库,等到后续再发
                messageService.saveToRedisWithUnreadMessages(message1,message1.getUser());
                session2.getBasicRemote().sendText("对方此时不在线哦^_^,请稍后再来 (此为系统消息)");
                log.info("用户{}发送消息失败 原因{}",userId,"用户不在线");
            }
            log.info("收到消息：{}", message2);
    }
}
